<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, ElTable, ElTableColumn, ElButton, ElInput, ElForm, ElFormItem, ElDialog, ElSelect, ElOption, ElPagination, ElDatePicker, ElSwitch } from 'element-plus';

// 课程数据
const courseData = ref([]);

// 搜索条件
const searchForm = reactive({
  courseName: '',
  subject: '',
  status: ''
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// 对话框状态
const dialogVisible = ref(false);
// 编辑模式
const editMode = ref(false);
// 当前编辑的课程ID
const currentCourseId = ref(null);
// 表单数据
const formData = reactive({
  courseName: '',
  subject: '',
  price: '',
  duration: '',
  level: '初级',
  status: true,
  description: ''
});

// 表单验证规则
const rules = {
  courseName: [
    { required: true, message: '请输入课程名称', trigger: 'blur' },
    { min: 1, max: 100, message: '课程名称长度在1到100个字符之间', trigger: 'blur' }
  ],
  subject: [
    { required: true, message: '请选择所属学科', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入课程价格', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的价格格式', trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '请输入课程时长', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入正确的时长格式', trigger: 'blur' }
  ]
};

// 表单引用
const courseFormRef = ref(null);

// 加载课程数据
const loadCourseData = () => {
  // 模拟API请求，使用静态数据
  courseData.value = [
    {
      id: 1,
      courseName: 'AI驱动Web开发',
      subject: 'AI大模型开发(Python)',
      price: '5999.00',
      duration: '40',
      level: '初级',
      status: true,
      createTime: '2025-06-20 09:00:00',
      description: '基于大模型技术的Web开发实战课程'
    },
    {
      id: 2,
      courseName: 'SpringAI大模型应用开发',
      subject: 'AI智能应用开发(Java)',
      price: '8999.00',
      duration: '60',
      level: '中级',
      status: true,
      createTime: '2025-06-20 09:05:00',
      description: '使用Spring框架整合AI大模型开发企业级应用'
    },
    {
      id: 3,
      courseName: '企业级物联网项目',
      subject: 'AI智能应用开发(Java)',
      price: '7999.00',
      duration: '50',
      level: '高级',
      status: true,
      createTime: '2025-06-20 09:10:00',
      description: '基于Java的企业级物联网项目开发实战'
    },
    {
      id: 4,
      courseName: 'RAG增强检索',
      subject: 'AI大模型开发(Python)',
      price: '4999.00',
      duration: '35',
      level: '中级',
      status: true,
      createTime: '2025-06-20 09:15:00',
      description: '检索增强生成(RAG)技术实战课程'
    },
    {
      id: 5,
      courseName: 'SpringCloud微服务架构',
      subject: 'AI智能应用开发(Java)',
      price: '6999.00',
      duration: '55',
      level: '高级',
      status: true,
      createTime: '2025-06-20 09:20:00',
      description: 'SpringCloud微服务架构设计与实战'
    },
    {
      id: 6,
      courseName: 'Python数据分析实战',
      subject: 'AI大模型开发(Python)',
      price: '5499.00',
      duration: '45',
      level: '初级',
      status: true,
      createTime: '2025-06-20 09:25:00',
      description: '使用Python进行数据分析和可视化'
    },
    {
      id: 7,
      courseName: 'Java并发编程',
      subject: 'AI智能应用开发(Java)',
      price: '6499.00',
      duration: '50',
      level: '中级',
      status: true,
      createTime: '2025-06-20 09:30:00',
      description: '深入理解Java并发编程原理与实践'
    },
    {
      id: 8,
      courseName: 'AI模型训练与优化',
      subject: 'AI大模型开发(Python)',
      price: '9999.00',
      duration: '70',
      level: '高级',
      status: true,
      createTime: '2025-06-20 09:35:00',
      description: '大模型训练、微调与优化实战课程'
    },
    {
      id: 9,
      courseName: 'Vue3+TypeScript项目开发',
      subject: 'AI智能应用开发(Java)',
      price: '5999.00',
      duration: '40',
      level: '初级',
      status: true,
      createTime: '2025-06-20 09:40:00',
      description: '使用Vue3和TypeScript开发前端项目'
    },
    {
      id: 10,
      courseName: 'Docker容器化部署',
      subject: 'AI大模型开发(Python)',
      price: '4999.00',
      duration: '30',
      level: '中级',
      status: true,
      createTime: '2025-06-20 09:45:00',
      description: 'Docker容器化技术与实践'
    },
    {
      id: 11,
      courseName: 'MySQL高性能优化',
      subject: 'AI智能应用开发(Java)',
      price: '5999.00',
      duration: '40',
      level: '中级',
      status: true,
      createTime: '2025-06-20 09:50:00',
      description: 'MySQL数据库性能优化实战'
    }
  ];
};

// 计算总数
const total = computed(() => courseData.value.length);

// 计算当前页显示的数据
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + Number(pageSize.value);
  return courseData.value.slice(start, end);
});

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
};

// 重置搜索条件
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  currentPage.value = 1;
};

// 处理分页
const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 切换课程状态
const toggleCourseStatus = (row) => {
  const newStatus = !row.status;
  ElMessageBox.confirm(
    `确定要将课程"${row.courseName}"${newStatus ? '启用' : '禁用'}吗？`,
    '状态变更确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    row.status = newStatus;
    ElMessage.success(newStatus ? '课程已启用' : '课程已禁用');
  }).catch(() => {
    // 取消状态变更，需要恢复原状态（因为switch组件已经改变了值）
    row.status = !newStatus;
  });
};

// 打开添加对话框
const openAddDialog = () => {
  editMode.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (row) => {
  editMode.value = true;
  currentCourseId.value = row.id;
  Object.assign(formData, row);
  dialogVisible.value = true;
};

// 删除课程
const deleteCourse = (row) => {
  ElMessageBox.confirm('确定要删除该课程吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = courseData.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      courseData.value.splice(index, 1);
      ElMessage.success('删除成功');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 保存课程
const saveCourse = () => {
  courseFormRef.value.validate((valid) => {
    if (valid) {
      const now = new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-');
      
      if (editMode.value) {
        // 编辑模式
        const index = courseData.value.findIndex(item => item.id === currentCourseId.value);
        if (index !== -1) {
          Object.assign(courseData.value[index], formData);
          ElMessage.success('编辑成功');
        }
      } else {
        // 添加模式
        const newCourse = {
          id: Date.now(), // 模拟生成唯一ID
          ...formData,
          createTime: now
        };
        courseData.value.push(newCourse);
        ElMessage.success('添加成功');
      }
      dialogVisible.value = false;
      resetForm();
    }
  });
};

// 重置表单
const resetForm = () => {
  if (courseFormRef.value) {
    courseFormRef.value.resetFields();
  }
  Object.keys(formData).forEach(key => {
    formData[key] = '';
  });
  formData.level = '初级';
  formData.status = true;
  currentCourseId.value = null;
};

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
  resetForm();
};

// 组件挂载时加载数据
onMounted(() => {
  loadCourseData();
});
</script>

<template>
  <div class="course-container">
    <div class="search-bar">
      <div class="search-item">
        <label>课程名称</label>
        <ElInput v-model="searchForm.courseName" placeholder="请输入" style="width: 200px;"></ElInput>
      </div>
      <div class="search-item">
        <label>所属学科</label>
        <ElSelect v-model="searchForm.subject" placeholder="请选择" style="width: 200px;">
          <ElOption label="AI大模型开发(Python)" value="AI大模型开发(Python)"></ElOption>
          <ElOption label="AI智能应用开发(Java)" value="AI智能应用开发(Java)"></ElOption>
          <ElOption label="AI鸿蒙开发" value="AI鸿蒙开发"></ElOption>
        </ElSelect>
      </div>
      <div class="search-item">
        <label>课程状态</label>
        <ElSelect v-model="searchForm.status" placeholder="请选择" style="width: 120px;">
          <ElOption label="启用" value="true"></ElOption>
          <ElOption label="禁用" value="false"></ElOption>
        </ElSelect>
      </div>
      <ElButton type="primary" @click="handleSearch">搜索</ElButton>
      <ElButton @click="handleReset">重置</ElButton>
    </div>
    
    <div class="course-header">
      <ElButton type="primary" @click="openAddDialog">+ 新增课程</ElButton>
    </div>
    
    <div class="course-content">
      <ElTable 
        v-if="courseData.length > 0"
        :data="currentPageData" 
        style="width: 100%; height: calc(100% - 60px);"
        stripe
        border
        fit
      >
        <ElTableColumn type="index" label="序号" min-width="80"></ElTableColumn>
        <ElTableColumn 
          prop="courseName" 
          label="课程名称" 
          min-width="180"
        />
        <ElTableColumn 
          prop="subject" 
          label="所属学科" 
          min-width="180"
        />
        <ElTableColumn 
          prop="price" 
          label="课程价格" 
          min-width="100"
          align="right"
          formatter="￥{row.price}"
        />
        <ElTableColumn 
          prop="duration" 
          label="课程时长(小时)" 
          min-width="120"
        />
        <ElTableColumn 
          prop="level" 
          label="课程等级" 
          min-width="100"
        >
          <template #default="{ row }">
            <span class="level-tag" :class="row.level === '初级' ? 'level-beginner' : row.level === '中级' ? 'level-intermediate' : 'level-advanced'">
              {{ row.level }}
            </span>
          </template>
        </ElTableColumn>
        <ElTableColumn 
          prop="status" 
          label="课程状态" 
          min-width="100"
          align="center"
        >
          <template #default="{ row }">
            <ElSwitch
              v-model="row.status"
              @change="toggleCourseStatus(row)"
              active-color="#13ce66"
              inactive-color="#ccc"
            ></ElSwitch>
          </template>
        </ElTableColumn>
        <ElTableColumn 
          prop="createTime" 
          label="创建时间" 
          min-width="180"
        />
        <ElTableColumn 
          label="操作" 
          min-width="120" 
          fixed="right"
        >
          <template #default="{ row }">
            <div class="action-buttons">
              <ElButton 
                type="text" 
                @click="openEditDialog(row)"
                size="small" 
                style="color: #409EFF;"
              >
                修改
              </ElButton>
              <ElButton 
                type="text" 
                @click="deleteCourse(row)"
                size="small" 
                style="color: #F56C6C;"
              >
                删除
              </ElButton>
            </div>
          </template>
        </ElTableColumn>
      </ElTable>
      <div v-else class="empty-data">暂无课程数据</div>
      
      <!-- 分页组件 -->
      <div class="pagination">
        <span class="total">共 {{ total }} 条</span>
        <ElSelect v-model="pageSize" @change="handleSizeChange" style="width: 100px;">
          <ElOption label="10条/页" value="10"></ElOption>
          <ElOption label="20条/页" value="20"></ElOption>
          <ElOption label="50条/页" value="50"></ElOption>
        </ElSelect>
        <ElPagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          layout="prev, pager, next, jumper"
        ></ElPagination>
      </div>
    </div>
    
    <!-- 添加/编辑课程对话框 -->
    <ElDialog
      :title="editMode ? '编辑课程' : '新增课程'"
      v-model="dialogVisible"
      width="600px"
      @close="closeDialog"
    >
      <ElForm
        ref="courseFormRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <ElFormItem label="课程名称" prop="courseName">
          <ElInput v-model="formData.courseName" placeholder="请输入课程名称" />
        </ElFormItem>
        <ElFormItem label="所属学科" prop="subject">
          <ElSelect v-model="formData.subject" placeholder="请选择">
            <ElOption label="AI大模型开发(Python)" value="AI大模型开发(Python)"></ElOption>
            <ElOption label="AI智能应用开发(Java)" value="AI智能应用开发(Java)"></ElOption>
            <ElOption label="AI鸿蒙开发" value="AI鸿蒙开发"></ElOption>
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="课程价格" prop="price">
          <ElInput v-model="formData.price" placeholder="请输入课程价格" />
        </ElFormItem>
        <ElFormItem label="课程时长(小时)" prop="duration">
          <ElInput v-model="formData.duration" placeholder="请输入课程时长" />
        </ElFormItem>
        <ElFormItem label="课程等级">
          <ElSelect v-model="formData.level" placeholder="请选择">
            <ElOption label="初级" value="初级"></ElOption>
            <ElOption label="中级" value="中级"></ElOption>
            <ElOption label="高级" value="高级"></ElOption>
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="课程状态">
          <ElSwitch v-model="formData.status" active-color="#13ce66" inactive-color="#ccc"></ElSwitch>
        </ElFormItem>
        <ElFormItem label="课程描述">
          <ElInput v-model="formData.description" type="textarea" rows="4" placeholder="请输入课程描述" />
        </ElFormItem>
      </ElForm>
      
      <template #footer>
        <ElButton @click="closeDialog">取消</ElButton>
        <ElButton type="primary" @click="saveCourse">确定</ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped>
/* 确保body没有默认margin */
:global(body) {
  margin: 0;
  padding: 0;
}

.course-container {
  padding: 15px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  box-sizing: border-box;
}

/* 搜索栏样式 */
.search-bar {
  background: #fff;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-item label {
  white-space: nowrap;
  font-weight: 500;
  color: #606266;
}

.course-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 15px;
}

.course-content {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.empty-data {
  text-align: center;
  padding: 100px 0;
  color: #999;
  font-size: 16px;
}

/* 自定义表格样式 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  width: 100%;
}

:deep(.el-table__header th) {
  background-color: #fafafa;
  font-weight: 600;
  color: #333;
  padding: 15px 0;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa;
}

:deep(.el-table__row) {
  height: 60px;
}

:deep(.el-button--small) {
  padding: 8px 16px;
}

/* 等级标签样式 */
.level-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  font-weight: 500;
}

.level-beginner {
  background-color: #e6f7ff;
  color: #1890ff;
}

.level-intermediate {
  background-color: #f6ffed;
  color: #52c41a;
}

.level-advanced {
  background-color: #fff2e8;
  color: #fa8c16;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
  gap: 15px;
  flex-shrink: 0;
}

.pagination .total {
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 5px;
}

/* 操作按钮样式 */
:deep(.el-button--text) {
  padding: 8px 10px;
}
</style>